package com.vito.oa.email.action;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;

import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Provider;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sun.mail.imap.IMAPFolder;
import com.vito.base.authoriza.action.BaseAction;
import com.vito.base.authoriza.cache.SessionMap;
import com.vito.base.authoriza.model.UserModel;
import com.vito.base.model.DataGrid;
import com.vito.base.model.ResMsg;
import com.vito.base.model.Result;
import com.vito.base.util.SpringApplicationContext;
import com.vito.base.util.StringUtil;
import com.vito.base.util.Validata;
import com.vito.oa.email.model.ExternalContacts;
import com.vito.oa.email.model.OaEmailConfig;
import com.vito.oa.email.model.OaEmailContant;
import com.vito.oa.email.model.OaEmailMessage;
import com.vito.oa.email.model.OaEmailSignModel;
import com.vito.oa.email.model.OaJamesUser;
import com.vito.oa.email.model.VitoImapProvider;
import com.vito.oa.email.model.VitoImapStore;
import com.vito.oa.email.service.OaEmailService;
import com.vito.oa.email.service.OaJamesUserService;
import com.vito.oa.email.sign.service.OaEmailSignService;
import com.vito.oa.email.util.OaEmailUtil;

import redis.clients.jedis.tool.JedisTool;

import com.vito.oa.email.service.ExternalContactsGroupService;
import com.vito.oa.email.service.ExternalContactsService;
import com.vito.oa.email.service.IEmailMbeanService;
import com.vito.oa.email.service.OaBaseUserService;

@Controller
@RequestMapping("oa/email")
public class OaEmailAction extends BaseAction {
	
	private static final Logger log = LoggerFactory.getLogger(OaEmailAction.class);
	
	private static String projectIP = StringUtil.getProperties("conf/email","project.IP");
	private static String host = StringUtil.getProperties("conf/email","email.host");
	private static String inboxFolder = StringUtil.getProperties("conf/email","email.inbox.folder");
	private static String sentFolder = StringUtil.getProperties("conf/email","email.sent.folder");
	private static String draftFolder = StringUtil.getProperties("conf/email","email.draft.folder");
	
	private static String recycleFolder = StringUtil.getProperties("conf/email", "email.recycle.folder");
	
	private static String nameSpace = StringUtil.getProperties("conf/email","email.name.space");
	private static String url = StringUtil.getProperties("conf/email","email.url");
	private static String vitoMail = StringUtil.getProperties("conf/email","email.vito.mail");
	private static String proxyAuthUrl = StringUtil.getProperties("conf/email","email.proxyAuth.url");
	private static String port = StringUtil.getProperties("conf/email","email.port");
	
	private static final String[] USER = { StringUtil.getProperties("conf/email","email.jmx.control.role"), StringUtil.getProperties("conf/email","email.jmx.user") };
	private static final String JMXServiceURL = StringUtil.getProperties("conf/email","email.jmx.service.url");
	
	private static String sendHost = StringUtil.getProperties("conf/email","email.send.host");
	private static String sendUrl = StringUtil.getProperties("conf/email","email.send.url");
	
	
	@Reference
	private OaEmailService emailService;
	
	@Reference
	private IEmailMbeanService iEmailMbeanService;
	
	@Reference
	private ExternalContactsService contactsService;
	
	@Reference
	private OaJamesUserService jamesUserService;
	
	@Reference
	private OaBaseUserService oaBaseUserService;
	
	@Reference
	private OaEmailSignService oaEmailSignService;
	
	@Reference
	private ExternalContactsGroupService contactsGroupService;
	
	private OaEmailConfig initConfig(HttpServletRequest request, Integer transferType) {
		UserModel user = SessionMap.getObj();
		Map<String, Integer> map = new HashMap<String, Integer>();
		OaEmailConfig emailConfig = new OaEmailConfig();
		if (user == null || Validata.isNullOrEmpty(user.getUserId())) {
			map.put("errorCode", Result.CODE_LOGIN_REQUIRE);
			emailConfig.setRunflag(map);
			emailConfig.setReturnMsg(ResMsg.MSG_LOGIN_NEED);
			log.info("没有登录");
			return emailConfig;
		}
		if (StringUtils.isBlank(user.getEmail())) {
			map.put("errorCode", Result.CODE_PARA_ERROR);
			emailConfig.setRunflag(map);
			emailConfig.setReturnMsg("没有邮箱号");
			log.info("没有邮箱号");
			return emailConfig;
		}
		String email[] = user.getEmail().split("@");
		if (email.length <= 0 || !vitoMail.equals(email[1])) {
			map.put("errorCode", Result.CODE_PARA_ERROR);
			emailConfig.setRunflag(map);
			emailConfig.setReturnMsg("邮箱账号不是@"+ vitoMail + "邮箱账号,请设置");
			log.info("邮箱账号不是@"+ vitoMail + "邮箱账号，请设置");
			return emailConfig;
		}
		emailConfig.setUserId(user.getUserId());
		emailConfig.setEmail(user.getEmail());
		emailConfig.setPersonal(user.getUserName());
		Properties props = new Properties();
		String sessionid = request == null ? SpringApplicationContext.getSessionId() : SpringApplicationContext.getSessionId(request);
		String ip = projectIP;
		Store store = null;
//		try {
//			ip = InetAddress.getLocalHost().getHostAddress();
//		} catch (UnknownHostException e) {
//			log.info("邮件获取ip失败");
//			e.printStackTrace();
//		}
		String path = request.getScheme()+"://"+ip+":"+request.getServerPort();
		String hrefPath = path + StringUtil.getWebRootPath() + proxyAuthUrl + sessionid+"&userid="+user.getUserId();
		log.info("email proxyauth:" + hrefPath);
		props.setProperty("mail.imap.proxyauth.user", hrefPath);
		props.setProperty("mail.imap.class", VitoImapStore.class.getName());
		props.setProperty("LOGINDISABLED", "true");
		Session session = Session.getInstance(props);
		session.addProvider(new VitoImapProvider(Provider.Type.STORE, "imap", null, "Sun Microsystems, Inc", null));
		String urlName = "";
		if (transferType == OaEmailConstant.TRANSFER_TYPE_GET) {
			emailConfig.setHost(host);
			urlName = url;
		}
		if (transferType == OaEmailConstant.TRANSFER_TYPE_SEND) {
			emailConfig.setHost(sendHost);
			urlName = sendUrl;
			emailConfig.setPort(port);
		}
		URLName urln = new URLName(urlName);
		try {
			store = session.getStore(urln);
			store.connect();
			emailConfig.setUrlName(urlName);
			emailConfig.setHrefPath(hrefPath);
			emailConfig.setStore(store);
		} catch (Exception e) {
			log.info("连接邮件服务器失败");
			map.put("errorCode", Result.CODE_ERROR);
			emailConfig.setRunflag(map);
			emailConfig.setReturnMsg("连接邮件服务器失败");
			e.printStackTrace();
			return emailConfig;
		}
		// 获得收件箱 
		try {
			boolean hasSentFolder = false;
			boolean hasDraftFolder = false;
			boolean hasRecycleFolder = false;
			Folder defaultFolder = store.getDefaultFolder();
			Folder[] allFolder = defaultFolder.list();
			for (int i = 0; i < allFolder.length; i++) {
				if (sentFolder.equals(allFolder[i].getFullName())) {
					hasSentFolder = true;
				}
				if (draftFolder.equals(allFolder[i].getFullName())) {
					hasDraftFolder = true;
				}
				if (recycleFolder.equals(allFolder[i].getFullName())){
					hasRecycleFolder = true;
				}
			}
			if (!hasSentFolder) {
				//创建发件箱
				String msg = createEmailBox(user.getEmail(), sentFolder);
				if (StringUtils.isNotBlank(msg)) {
					if (!"success".equals(msg)) {
						map.put("errorCode", Result.CODE_ERROR);
						emailConfig.setRunflag(map);
						emailConfig.setReturnMsg(msg);
						return emailConfig;
					}
				} else {
					map.put("errorCode", Result.CODE_ERROR);
					emailConfig.setRunflag(map);
					emailConfig.setReturnMsg("创建发件箱失败");
					return emailConfig;
				}
			}
			if (!hasDraftFolder) {
				//创建草稿箱
				String msg = createEmailBox(user.getEmail(), draftFolder);
				if (StringUtils.isNotBlank(msg)) {
					if (!"success".equals(msg)) {
						map.put("errorCode", Result.CODE_ERROR);
						emailConfig.setRunflag(map);
						emailConfig.setReturnMsg(msg);
						return emailConfig;
					}
				} else {
					map.put("errorCode", Result.CODE_ERROR);
					emailConfig.setRunflag(map);
					emailConfig.setReturnMsg("创建发件箱失败");
					return emailConfig;
				}
			}
			if (!hasRecycleFolder){
				//创建回收箱
				String msg = createEmailBox(user.getEmail(), recycleFolder);
				if (StringUtils.isNotBlank(msg)) {
					if (!"success".equals(msg)) {
						map.put("errorCode", Result.CODE_ERROR);
						emailConfig.setRunflag(map);
						emailConfig.setReturnMsg(msg);
						return emailConfig;
					}
				} else {
					map.put("errorCode", Result.CODE_ERROR);
					emailConfig.setRunflag(map);
					emailConfig.setReturnMsg("创建回收箱失败");
					return emailConfig;
				}
			}
			if(defaultFolder!=null && defaultFolder.isOpen()){
				defaultFolder.close(true); 
	    	}
			//判断邮箱存储是否打开如果打开则将其关闭
//	    	if(store!=null && store.isConnected()){
//	    		store.close();
//	    	}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return emailConfig;
	}
	
	/**
	 * 创建邮箱
	 * @param email
	 * @param folderType
	 * @return
	 */
	private String createEmailBox(String email, String folderType) {
		String msg = "";
		int b = iEmailMbeanService.createEmailBox(nameSpace, email, folderType, USER, JMXServiceURL);
		if (b == OaEmailContant.CONNECT_FAILED) {
			msg = "JVM连接失败";
			log.info("【" + email + "】JVM连接失败");
		} else if (b == OaEmailContant.ALREADY_EXIST) {
			msg = folderType + "已存在";
			log.info("【" + email + "】创建" + folderType + "已存在");
		} else if (b == OaEmailContant.SUCCESS) {
			msg = "success";
			log.info("【" + email + "】创建" + folderType + "成功");
		} else {
			msg = "创建" + folderType + "失败";
			log.info("【" + email + "】创建" + folderType + "失败");
		}
		return msg;
	}
	
	@ResponseBody
	@RequestMapping(value = "/proxyAuth")
	public String getConnectInfo(String sessionid) {
		if (StringUtils.isNotBlank(sessionid)) {
			UserModel user = SessionMap.getObj(sessionid);
			if (user != null && StringUtils.isNotBlank(user.getEmail())) {
				log.info("email proxyAuth emailAddress:" + user.getEmail());
				return user.getEmail();
			}
		}
		return "";
	}
	
	/**
	 * 收件箱列表
	 * @param emailMessage
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getInboxEmail")
	public Result getInboxEmail(OaEmailMessage emailMessage, HttpServletRequest request) {
		Result rs = new Result();
		try {
			OaEmailConfig emailConfig = initConfig(request, OaEmailConstant.TRANSFER_TYPE_GET);
			if (emailConfig.getRunflag() != null && emailConfig.getRunflag().get("errorCode") != null) {
				rs.setCode(emailConfig.getRunflag().get("errorCode"));
				rs.setMsg(emailConfig.getReturnMsg());
				return rs;
			}
			emailConfig.setFolder(inboxFolder);
			emailConfig.setFolderType(OaEmailConstant.FOLDER_TYPE_INBOX);
			DataGrid<OaEmailMessage> list = OaEmailUtil.getEmailPage(emailMessage, emailConfig);
			if(list!=null&&list.getTotal()>0){
				rs.setCode(Result.CODE_OK);
				rs.setData(list);
				return rs;
			}else{
				rs.setCode(Result.CODE_NO_DATA);
				rs.setMsg("没有数据");
				return rs;
			}
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	
	/**
	 * 回收箱列表
	 * @param emailMessage
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getRecycleEmail")
	public Result getRecycleEmail(OaEmailMessage emailMessage, HttpServletRequest request) {
		Result rs = new Result();
		try {
			OaEmailConfig emailConfig = initConfig(request, OaEmailConstant.TRANSFER_TYPE_GET);
			if (emailConfig.getRunflag() != null && emailConfig.getRunflag().get("errorCode") != null) {
				rs.setCode(emailConfig.getRunflag().get("errorCode"));
				rs.setMsg(emailConfig.getReturnMsg());
				return rs;
			}
			emailConfig.setFolder(recycleFolder);
			emailConfig.setFolderType(OaEmailConstant.FOLDER_TYPE_RECYCLE);
			DataGrid<OaEmailMessage> list = OaEmailUtil.getRecycleEmaile(emailMessage, emailConfig);
			if(list!=null&&list.getTotal()>0){
				rs.setCode(Result.CODE_OK);
				rs.setData(list);
				return rs;
			}else{
				rs.setCode(Result.CODE_NO_DATA);
				rs.setMsg("没有数据");
				return rs;
			}
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	
	
	
	/**
	 * 已发送邮件
	 * @param emailMessage
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getSentEmail")
	public Result getSentEmail(OaEmailMessage emailMessage, HttpServletRequest request) {
		Result rs = new Result();
		try {
			OaEmailConfig emailConfig = initConfig(request, OaEmailConstant.TRANSFER_TYPE_GET);
			if (emailConfig.getRunflag() != null && emailConfig.getRunflag().get("errorCode") != null) {
				rs.setCode(emailConfig.getRunflag().get("errorCode"));
				rs.setMsg(emailConfig.getReturnMsg());
				return rs;
			}
			emailConfig.setFolder(sentFolder);
			emailConfig.setFolderType(OaEmailConstant.FOLDER_TYPE_SEND);
			DataGrid<OaEmailMessage> list = OaEmailUtil.getSentEmailPage(emailMessage, emailConfig);
			if (list != null && list.getTotal() > 0){
				rs.setCode(Result.CODE_OK);
				rs.setData(list);
				return rs;
			}else{
				rs.setCode(Result.CODE_NO_DATA);
				rs.setMsg("没有数据");
				return rs;
			}
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	
	/**
	 * 草稿箱
	 * @param emailMessage
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getDraftEmail")
	public Result getDraftEmail(OaEmailMessage emailMessage, HttpServletRequest request) {
		Result rs = new Result();
		try {
			OaEmailConfig emailConfig = initConfig(request, OaEmailConstant.TRANSFER_TYPE_GET);
			if (emailConfig.getRunflag() != null && emailConfig.getRunflag().get("errorCode") != null) {
				rs.setCode(emailConfig.getRunflag().get("errorCode"));
				rs.setMsg(emailConfig.getReturnMsg());
				return rs;
			}
			emailConfig.setFolder(draftFolder);
			emailConfig.setFolderType(OaEmailConstant.FOLDER_TYPE_DRAFT);
			DataGrid<OaEmailMessage> list = OaEmailUtil.getDraftEmailPage(emailMessage, emailConfig);
			if(list!=null&&list.getTotal()>0){
				rs.setCode(Result.CODE_OK);
				rs.setData(list);
				return rs;
			}else{
				rs.setCode(Result.CODE_NO_DATA);
				rs.setMsg("没有数据");
				return rs;
			}
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	
	/**
	 * 查看邮件
	 * @param emailMessage
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getViewEmail")
	public Result getViewEmail(Long number, Integer folderType, HttpServletRequest request) {
		Result rs = new Result();
		try {
			if (number == null) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("邮件number不能为空");
				return rs;
			}
			if (folderType == null) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("文件夹类型不能为空");
				return rs;
			}
			OaEmailConfig emailConfig = initConfig(request, OaEmailConstant.TRANSFER_TYPE_GET);
			if (emailConfig.getRunflag() != null && emailConfig.getRunflag().get("errorCode") != null) {
				rs.setCode(emailConfig.getRunflag().get("errorCode"));
				rs.setMsg(emailConfig.getReturnMsg());
				return rs;
			}
			// 1、收件箱 2、发件箱、3草稿箱
			if (folderType == OaEmailConstant.FOLDER_TYPE_INBOX) {
				emailConfig.setFolder(inboxFolder);
			} else if (folderType == OaEmailConstant.FOLDER_TYPE_SEND) {
				emailConfig.setFolder(sentFolder);
			} else if (folderType == OaEmailConstant.FOLDER_TYPE_DRAFT) {
				emailConfig.setFolder(draftFolder);
			} else {
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("没有对应信箱");
				return rs;
			}
			String eKey = "email_obj_" + emailConfig.getUserId() + "_" + emailConfig.getEmail() + "_" + folderType + "_" + number;
			Object obj = JedisTool.getObject(eKey);
			OaEmailMessage em = null;
			if (obj != null) {
				log.info("getViewEmail cache key:" + eKey);
				em = (OaEmailMessage)obj;
			} else {
				em = OaEmailUtil.getViewEmail(number, folderType, emailConfig, oaBaseUserService);
				if (folderType == OaEmailConstant.FOLDER_TYPE_INBOX && em.isReplyTo()) {
					OaEmailMessage newEm = new OaEmailMessage();
					newEm.setNumber(number);
					newEm.setSeenFlag(em.isSeenFlag());
					newEm.setPriority(em.getPriority());
					newEm.setFromAddressList(em.getFromAddressList());
					newEm.setSubject(em.getSubject());
					newEm.setSendDate(em.getSendDate());
					newEm.setReceivedDate(em.getReceivedDate());
					newEm.setToAddressList(em.getToAddressList());
					newEm.setCcAddressList(em.getCcAddressList());
					newEm.setBccAddressList(em.getBccAddressList());
					newEm.setEmailText(em.getEmailText());
					newEm.setFileList(em.getFileList());
					newEm.setReplyTo(false);
					JedisTool.setObject(eKey, newEm);
				} else {
					JedisTool.setObject(eKey, em);
				}
				List<?> keyList = JedisTool.getList("email_obj_" + emailConfig.getUserId() + "_" + emailConfig.getEmail());
				if (keyList != null && keyList.size() > 0) {
					JedisTool.appendList("email_obj_" + emailConfig.getUserId() + "_" + emailConfig.getEmail(), eKey);
				} else {
					List<String> newKeyList = new ArrayList<String>();
					newKeyList.add(eKey);
					JedisTool.setList("email_obj_" + emailConfig.getUserId() + "_" + emailConfig.getEmail(), newKeyList);
				}
			}
			//处理首页列表缓存
			String eListKey = "email_list_" + emailConfig.getUserId() + "_" + emailConfig.getEmail() + "_" + folderType + "_" + number;
			Object indexObj = JedisTool.getObject(eListKey);
			if (indexObj != null) {
				JedisTool.del(eListKey);
				List<?> keyObjList = JedisTool.getList("email_list_" + emailConfig.getUserId() + "_" + emailConfig.getEmail());
				if (keyObjList != null && keyObjList.size() > 0) {
					keyObjList.remove(eListKey);
					JedisTool.setList("email_list_" + emailConfig.getUserId() + "_" + emailConfig.getEmail(), keyObjList);
				}
			}
			rs.setCode(Result.CODE_OK);
			rs.setData(em);
			return rs;
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	
	/**
	 * 清除缓存
	 * @param userId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/clearEmailCache")
	public Result clearEmailCache(String userId) {
		Result rs = new Result();
		try {
			UserModel user = SessionMap.getObj();
			if (user == null || Validata.isNullOrEmpty(user.getUserId()) || Validata.isNullOrEmpty(user.getDeptParentId())) {
				rs.setCode(Result.CODE_LOGIN_REQUIRE);
				rs.setMsg(ResMsg.MSG_LOGIN_NEED);
				return rs;
			}
			if (StringUtils.isBlank(userId)) {
				List<Map<String,String>> userlistDeptTree = oaBaseUserService.getInnerContactsTree(user.getDeptParentId());
				for (Map<String, String> map : userlistDeptTree) {
					if (map != null && map.get("id") != null && map.get("id") != "" && "USER".equals(map.get("type"))) {

						List<?> keyListList = JedisTool.getList("email_list_" + map.get("id") + "_" + map.get("email"));
						log.info("clearEmailCache 邮件列表 deptParentId【"+user.getDeptParentId()+"】 keys:" + keyListList.toString());
						if (keyListList != null && keyListList.size() > 0) {
							for (Object object : keyListList) {
								JedisTool.del(object.toString());
							}
							JedisTool.del("email_list_" + map.get("id") + "_" + map.get("email"));
						}
						List<?> keyObjList = JedisTool.getList("email_obj_" + map.get("id") + "_" + map.get("email"));
						log.info("clearEmailCache 邮件详情 deptParentId【"+user.getDeptParentId()+"】 keys:" + keyObjList.toString());
						if (keyObjList != null && keyObjList.size() > 0) {
							for (Object object : keyObjList) {
								JedisTool.del(object.toString());
							}
							JedisTool.del("email_obj_" + map.get("id") + "_" + map.get("email"));
						}
					}
				}
			}
			if (StringUtils.isNotBlank(userId) && "all".equals(userId)) {
				List<Map<String,String>> allUser = oaBaseUserService.getAllUserEmail();
				for (Map<String, String> map : allUser) {
					if (map != null && map.get("userId") != null) {

						List<?> keyListList = JedisTool.getList("email_list_" + map.get("userId") + "_" + map.get("email"));
						log.info("clearEmailCache all keys 邮件列表:" + keyListList.toString());
						if (keyListList != null && keyListList.size() > 0) {
							for (Object object : keyListList) {
								JedisTool.del(object.toString());
							}
							JedisTool.del("email_list_" + map.get("userId") + "_" + map.get("email"));
						}
						List<?> keyObjList = JedisTool.getList("email_obj_" + map.get("userId") + "_" + map.get("email"));
						log.info("clearEmailCache all keys 邮件详情 :" + keyObjList.toString());
						if (keyObjList != null && keyObjList.size() > 0) {
							for (Object object : keyObjList) {
								JedisTool.del(object.toString());
							}
							JedisTool.del("email_obj_" + map.get("userId") + "_" + map.get("email"));
						}
					}
				}
			} 
			if (StringUtils.isNotBlank(userId) && !"all".equals(userId)) {
				Map<String, Object> map = oaBaseUserService.getUserById(userId);
				List<?> keyListList = JedisTool.getList("email_list_" + userId + "_" + map.get("email").toString());
				log.info("clearEmailCache 邮件列表 userId【"+userId+"】 keys:" + keyListList.toString());
				if (keyListList != null && keyListList.size() > 0) {
					for (Object object : keyListList) {
						JedisTool.del(object.toString());
					}
					JedisTool.del("email_list_" + userId + "_" + map.get("email").toString());
				}
				List<?> keyObjList = JedisTool.getList("email_obj_" + userId + "_" + map.get("email").toString());
				log.info("clearEmailCache userId 【"+userId+"】  邮件详情 keys:" + keyObjList.toString());
				if (keyObjList != null && keyObjList.size() > 0) {
					for (Object object : keyObjList) {
						JedisTool.del(object.toString());
					}
					JedisTool.del("email_obj_" + userId + "_" + map.get("email").toString());
				}
			}
			
			rs.setCode(Result.CODE_OK);
			rs.setMsg("清除成功");
			return rs;
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	
	/**
	 * 发送邮件
	 * @param emailMessage
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/sendEmail")
	public Result sendEmail(OaEmailMessage emailMessage, HttpServletRequest request) {
		Result rs = new Result();
		try {
			if (emailMessage.getToAddressList() == null || emailMessage.getToAddressList().size() == 0) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("收件人不能为空");
				return rs;
			}
			if (Validata.isNullOrEmpty(emailMessage.getSubject())) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("主题不能为空");
				return rs;
			}
			//内容可以为空 5263
//			if (Validata.isNullOrEmpty(emailMessage.getEmailText())) {
//				rs.setCode(Result.CODE_PARA_ERROR);
//				rs.setMsg("内容不能为空");
//				return rs;
//			}
			OaEmailConfig emailConfig = initConfig(request, OaEmailConstant.TRANSFER_TYPE_SEND);
			if (emailConfig.getRunflag() != null && emailConfig.getRunflag().get("errorCode") != null) {
				rs.setCode(emailConfig.getRunflag().get("errorCode"));
				rs.setMsg(emailConfig.getReturnMsg());
				return rs;
			}
			emailConfig.setFolder(inboxFolder);
			List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
			Map<String, String> map = new HashMap<String, String>();
			map.put("personal", emailConfig.getPersonal());
			map.put("email", emailConfig.getEmail());
			mapList.add(map);
			emailMessage.setFromAddressList(mapList);
			boolean b = OaEmailUtil.sendEmail(emailMessage, emailConfig, false);
			if (b) {
				rs.setCode(Result.CODE_OK);
				rs.setMsg("发送成功");
			} else {
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("发送失败");
			}
			return rs;
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	
	/**
	 * 保存草稿邮件
	 * @param emailMessage
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/saveDraftEmail")
	public Result saveDraftEmail(OaEmailMessage emailMessage, HttpServletRequest request) {
		Result rs = new Result();
		try {
			OaEmailConfig emailConfig = initConfig(request, OaEmailConstant.TRANSFER_TYPE_SEND);
			if (emailConfig.getRunflag() != null && emailConfig.getRunflag().get("errorCode") != null) {
				rs.setCode(emailConfig.getRunflag().get("errorCode"));
				rs.setMsg(emailConfig.getReturnMsg());
				return rs;
			}
			if (Validata.isNullOrEmpty(emailMessage.getSubject())) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("标题不能为空");
				return rs;
			}
			if (Validata.isNullOrEmpty(emailMessage.getEmailText())) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("内容不能为空");
				return rs;
			}
			emailConfig.setFolder(inboxFolder);
			List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
			Map<String, String> map = new HashMap<String, String>();
			map.put("personal", emailConfig.getPersonal());
			map.put("email", emailConfig.getEmail());
			mapList.add(map);
			emailMessage.setFromAddressList(mapList);
			boolean b = OaEmailUtil.sendEmail(emailMessage, emailConfig, true);
			if (b) {
				rs.setCode(Result.CODE_OK);
				rs.setMsg("保存成功");
			} else {
				log.error("保存草稿邮件失败");
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("保存失败");
			}
			return rs;
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	
	/**
	 * 上传附件
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/uploadAttachment", method = RequestMethod.POST)
	public Result uploadAttachment(HttpServletRequest request) {
		Result rs = new Result();
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
			String folderPath = request.getSession().getServletContext().getRealPath("/") + "/resource/img/attUpload";
			String originalFilename = "";
			String returnFilePath = "";
			for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
				MultipartFile mf = entity.getValue();
				originalFilename = mf.getOriginalFilename(); //文件名
				String newFileName = getNewFileName(originalFilename);
				String filePath = getFolder(folderPath);
				File file = new File(filePath + "/" + newFileName);
				returnFilePath = filePath + "/" + newFileName;
				try {
					FileCopyUtils.copy(mf.getBytes(), file);
					System.out.println(returnFilePath);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			map.put("fileName", originalFilename);
			map.put("returnFilePath", returnFilePath);
			rs.setData(map);
			rs.setCode(Result.CODE_OK);
			return rs;
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	
	/**
	 * 删除文件
	 * @param filePath
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteAttachment")
	public Result deleteAttachment(String filePath) {
		Result rs = new Result();
		try {
			if (Validata.isNullOrEmpty(filePath)) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("文件路径不能为空");
				return rs;
			}
			boolean flag = false;
			File file = new File(filePath);
			//判断目录或文件是否存在
			if (!file.exists()) { //不存在
				flag = true;
			} else {
				//判断是否为文件
				if (file.isFile()) {
					file.delete();  
					flag = true;  
				}
			}
			if (flag) {
				rs.setMsg("删除成功");
				rs.setCode(Result.CODE_OK);
			} else {
				rs.setMsg("删除失败");
				rs.setCode(Result.CODE_ERROR);
			}
			return rs;
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	
	/**
	 * 回复
	 * @param emailMessage
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/replyEmail")
	public Result replyEmail(OaEmailMessage emailMessage, HttpServletRequest request) {
		Result rs = new Result();
		try {
			if (emailMessage.getToAddressList() == null || emailMessage.getToAddressList().size() <= 0) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("回复人不能为空");
				return rs;
			}
			if (Validata.isNullOrEmpty(emailMessage.getEmailText())) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("内容不能为空");
				return rs;
			}
			OaEmailConfig emailConfig = initConfig(request, OaEmailConstant.TRANSFER_TYPE_SEND);
			if (emailConfig.getRunflag() != null && emailConfig.getRunflag().get("errorCode") != null) {
				rs.setCode(emailConfig.getRunflag().get("errorCode"));
				rs.setMsg(emailConfig.getReturnMsg());
				return rs;
			}
			// 1、收件箱 2、发件箱、3草稿箱
			if (emailMessage.getFolderType() == OaEmailConstant.FOLDER_TYPE_INBOX) {
				emailConfig.setFolder(inboxFolder);
			} else if (emailMessage.getFolderType() == OaEmailConstant.FOLDER_TYPE_SEND) {
				emailConfig.setFolder(sentFolder);
			} else if (emailMessage.getFolderType() == OaEmailConstant.FOLDER_TYPE_DRAFT) {
				emailConfig.setFolder(draftFolder);
			} else {
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("没有对应信箱");
				return rs;
			}
			List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
			Map<String, String> map = new HashMap<String, String>();
			map.put("personal", emailConfig.getPersonal());
			map.put("email", emailConfig.getEmail());
			mapList.add(map);
			emailMessage.setFromAddressList(mapList);
			boolean b = OaEmailUtil.replyEmail(emailMessage, emailConfig, true);
			if (b) {
				rs.setCode(Result.CODE_OK);
				rs.setMsg("发送成功");
			} else {
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("发送失败");
			}
			return rs;
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	/**
	 * 转发
	 * @param emailMessage
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/forwardEmail")
	public Result forwardEmail(OaEmailMessage emailMessage, HttpServletRequest request) {
		Result rs = new Result();
		try {
			if (emailMessage.getToAddressList() == null) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("转发人不能为空");
				return rs;
			}
			if (Validata.isNullOrEmpty(emailMessage.getSubject())) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("主题不能为空");
				return rs;
			}
			if (Validata.isNullOrEmpty(emailMessage.getEmailText())) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("内容不能为空");
				return rs;
			}
			OaEmailConfig emailConfig = initConfig(request, OaEmailConstant.TRANSFER_TYPE_SEND);
			if (emailConfig.getRunflag() != null && emailConfig.getRunflag().get("errorCode") != null) {
				rs.setCode(emailConfig.getRunflag().get("errorCode"));
				rs.setMsg(emailConfig.getReturnMsg());
				return rs;
			}
			// 1、收件箱 2、发件箱、3草稿箱
			if (emailMessage.getFolderType() == OaEmailConstant.FOLDER_TYPE_INBOX) {
				emailConfig.setFolder(inboxFolder);
			} else if (emailMessage.getFolderType() == OaEmailConstant.FOLDER_TYPE_SEND) {
				emailConfig.setFolder(sentFolder);
			} else if (emailMessage.getFolderType() == OaEmailConstant.FOLDER_TYPE_DRAFT) {
				emailConfig.setFolder(draftFolder);
			} else {
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("没有对应信箱");
				return rs;
			}
			List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
			Map<String, String> map = new HashMap<String, String>();
			map.put("personal", emailConfig.getPersonal());
			map.put("email", emailConfig.getEmail());
			mapList.add(map);
			emailMessage.setFromAddressList(mapList);
			boolean b = OaEmailUtil.forwardEmail(emailMessage, emailConfig, true);
			if (b) {
				rs.setCode(Result.CODE_OK);
				rs.setMsg("发送成功");
			} else {
				log.error("转发失败");
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("转发失败");
			}
			return rs;
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	
	/**
	 * 草稿箱邮件发送
	 * @param emailMessage
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/draftSendEmail")
	public Result draftSendEmail(OaEmailMessage emailMessage, HttpServletRequest request) {
		Result rs = new Result();
		try {
			if (emailMessage.getToAddressList() == null) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("收件人不能为空");
				return rs;
			}
			if (Validata.isNullOrEmpty(emailMessage.getSubject())) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("主题不能为空");
				return rs;
			}
			if (Validata.isNullOrEmpty(emailMessage.getEmailText())) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("内容不能为空");
				return rs;
			}
			OaEmailConfig emailConfig = initConfig(request, OaEmailConstant.TRANSFER_TYPE_SEND);
			if (emailConfig.getRunflag() != null && emailConfig.getRunflag().get("errorCode") != null) {
				rs.setCode(emailConfig.getRunflag().get("errorCode"));
				rs.setMsg(emailConfig.getReturnMsg());
				return rs;
			}
			// 1、收件箱 2、发件箱、3草稿箱
			if (emailMessage.getFolderType() == OaEmailConstant.FOLDER_TYPE_INBOX) {
				emailConfig.setFolder(inboxFolder);
			} else if (emailMessage.getFolderType() == OaEmailConstant.FOLDER_TYPE_SEND) {
				emailConfig.setFolder(sentFolder);
			} else if (emailMessage.getFolderType() == OaEmailConstant.FOLDER_TYPE_DRAFT) {
				emailConfig.setFolder(draftFolder);
			} else {
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("没有对应信箱");
				return rs;
			}
			List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
			Map<String, String> map = new HashMap<String, String>();
			map.put("personal", emailConfig.getPersonal());
			map.put("email", emailConfig.getEmail());
			mapList.add(map);
			emailMessage.setFromAddressList(mapList);
			boolean b = OaEmailUtil.draftSendEmail(emailMessage, emailConfig, true);
			if (b) {
				rs.setCode(Result.CODE_OK);
				rs.setMsg("发送成功");
			} else {
				log.error("草稿箱邮件发送失败");
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("发送失败");
			}
			return rs;
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	
	/**
	 * 草稿邮件再次保存
	 * @param emailMessage
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/saveDraftAgainEmail")
	public Result saveDraftAgainEmail(OaEmailMessage emailMessage, HttpServletRequest request) {
		Result rs = new Result();
		try {
			if (Validata.isNullOrEmpty(emailMessage.getSubject())) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("主题不能为空");
				return rs;
			}
			if (Validata.isNullOrEmpty(emailMessage.getEmailText())) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("内容不能为空");
				return rs;
			}
			OaEmailConfig emailConfig = initConfig(request, OaEmailConstant.TRANSFER_TYPE_SEND);
			if (emailConfig.getRunflag() != null && emailConfig.getRunflag().get("errorCode") != null) {
				rs.setCode(emailConfig.getRunflag().get("errorCode"));
				rs.setMsg(emailConfig.getReturnMsg());
				return rs;
			}
			//草稿箱
			emailConfig.setFolder(draftFolder);
			List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
			Map<String, String> map = new HashMap<String, String>();
			map.put("personal", emailConfig.getPersonal());
			map.put("email", emailConfig.getEmail());
			mapList.add(map);
			emailMessage.setFromAddressList(mapList);
			boolean b = OaEmailUtil.saveDraftAgainEmail(emailMessage, emailConfig);
			if (b) {
				rs.setCode(Result.CODE_OK);
				rs.setMsg("保存成功");
			} else {
				log.error("草稿邮件再次保存失败");
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("保存失败");
			}
			return rs;
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	
	/**
	 * 公共请求接口
	 * @param json
	 * @param method
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/invoke")
	public Result invoke(String json, String method ,HttpServletRequest request){
		Result rs = new Result();
		try {
			UserModel user = SessionMap.getObj();
			if (user == null || Validata.isNullOrEmpty(user.getUserId())) {
				rs.setCode(Result.CODE_LOGIN_REQUIRE);
				rs.setMsg(ResMsg.MSG_LOGIN_NEED);
				return rs;
			}
			OaEmailMessage emailMessage = null;
			try {
				JSONObject job = JSON.parseObject(json);
				emailMessage = JSON.toJavaObject(job, OaEmailMessage.class);
			} catch (Exception e) {
				log.error("json转java对象OaEmailMessage出错：",e);
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("json转java对象出错");
				return rs;
			}
			Class<? extends OaEmailAction> clazz = this.getClass();
			if (emailMessage != null) {
				List<Map<String, String>> toaddrList = emailMessage.getToAddressList();
				List<Map<String, String>> ccaddrList = emailMessage.getCcAddressList();
				List<Map<String, String>> bccaddrList = emailMessage.getBccAddressList();
				if (toaddrList != null || ccaddrList != null || bccaddrList != null) {
					//查询外部联系人树
					List<ExternalContacts> externalList = contactsService.getEmailContactsList(user.getUserId());
					if (externalList != null && externalList.size() > 0) {
						for (ExternalContacts external : externalList) {
							if (toaddrList != null && toaddrList.size() > 0) {
								for (Map<String, String> map : toaddrList) {
									if (external.getContactsMail() != null && external.getContactsMail().equals(map.get("email"))) {
										map.put("personal", external.getContactsName());
									}
								}
							}
							if (ccaddrList != null && ccaddrList.size() > 0) {
								for (Map<String, String> map : ccaddrList) {
									if (external.getContactsMail() != null && external.getContactsMail().equals(map.get("email"))) {
										map.put("personal", external.getContactsName());
									}
								}
							}
							if (bccaddrList != null && bccaddrList.size() > 0) {
								for (Map<String, String> map : bccaddrList) {
									if (external.getContactsMail() != null && external.getContactsMail().equals(map.get("email"))) {
										map.put("personal", external.getContactsName());
									}
								}
							}
						}
					}
					//查询内部联系人
					List<Map<String,String>> innerList = oaBaseUserService.getInnerContactsTree(user.getDeptParentId());
					if (innerList != null && innerList.size() > 0) {
						for (Map<String, String> inner : innerList) {
							if (toaddrList != null && toaddrList.size() > 0) {
								for (Map<String, String> map : toaddrList) {
									if (inner.get("email") != null && inner.get("email").equals(map.get("email"))) {
										map.put("personal", inner.get("name"));
									}
								}
							}
							if (ccaddrList != null && ccaddrList.size() > 0) {
								for (Map<String, String> map : ccaddrList) {
									if (inner.get("email") != null && inner.get("email").equals(map.get("email"))) {
										map.put("personal", inner.get("name"));
									}
								}
							}
							if (bccaddrList != null && bccaddrList.size() > 0) {
								for (Map<String, String> map : bccaddrList) {
									if (inner.get("email") != null && inner.get("email").equals(map.get("email"))) {
										map.put("personal", inner.get("name"));
									}
								}
							}
						}
					}
					emailMessage.setToAddressList(toaddrList);
					emailMessage.setCcAddressList(ccaddrList);
					emailMessage.setBccAddressList(bccaddrList);
				}
			}
			try {
				Method m = clazz.getDeclaredMethod(method,OaEmailMessage.class,HttpServletRequest.class);
				return (Result)m.invoke(this, emailMessage, request);
			} catch (Exception e) {
				log.error("调用公共请求接口invoke出错:" + e);
				e.printStackTrace();
			}
			return rs;
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
		
	}
	
	/**
	 * 转发或回复邮件保存草稿邮件
	 * @param emailMessage
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/saveReplyForwardDraftEmail")
	public Result saveReplyForwardDraftEmail(OaEmailMessage emailMessage, HttpServletRequest request) {
		Result rs = new Result();
		try {
			if (Validata.isNullOrEmpty(emailMessage.getEmailText())) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("内容不能为空");
				return rs;
			}
			OaEmailConfig emailConfig = initConfig(request, OaEmailConstant.TRANSFER_TYPE_SEND);
			if (emailConfig.getRunflag() != null && emailConfig.getRunflag().get("errorCode") != null) {
				rs.setCode(emailConfig.getRunflag().get("errorCode"));
				rs.setMsg(emailConfig.getReturnMsg());
				return rs;
			}
			// 1、收件箱 2、发件箱、3草稿箱
			if (emailMessage.getFolderType() == OaEmailConstant.FOLDER_TYPE_INBOX) {
				emailConfig.setFolder(inboxFolder);
			} else if (emailMessage.getFolderType() == OaEmailConstant.FOLDER_TYPE_SEND) {
				emailConfig.setFolder(sentFolder);
			} else if (emailMessage.getFolderType() == OaEmailConstant.FOLDER_TYPE_DRAFT) {
				emailConfig.setFolder(draftFolder);
			} else {
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("没有对应信箱");
				return rs;
			}
			List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
			Map<String, String> map = new HashMap<String, String>();
			map.put("personal", emailConfig.getPersonal());
			map.put("email", emailConfig.getEmail());
			mapList.add(map);
			emailMessage.setFromAddressList(mapList);
			boolean b = OaEmailUtil.saveReplyForwardDraftEmail(emailMessage, emailConfig);
			if (b) {
				rs.setCode(Result.CODE_OK);
				rs.setMsg("保存成功");
			} else {
				log.error("转发或回复邮件保存草稿邮件失败");
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("保存失败");
			}
			return rs;
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	/**
	 * 删除收件箱邮件
	 * @param emailMessage
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteEmail")
	public Result deleteEmail(Long number, Integer folderType, HttpServletRequest request) {
		Result rs = new Result();
		try {
			if (number == null) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("邮件number不能为空");
				return rs;
			}
			if (folderType == null) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("文件夹类型不能为空");
				return rs;
			}
			OaEmailConfig emailConfig = initConfig(request, OaEmailConstant.TRANSFER_TYPE_GET);
			if (emailConfig.getRunflag() != null && emailConfig.getRunflag().get("errorCode") != null) {
				rs.setCode(emailConfig.getRunflag().get("errorCode"));
				rs.setMsg(emailConfig.getReturnMsg());
				return rs;
			}
			// 1、收件箱 2、发件箱、3草稿箱、4回收箱
			if (folderType == OaEmailConstant.FOLDER_TYPE_INBOX) {
				emailConfig.setFolder(inboxFolder);
			} else if (folderType == OaEmailConstant.FOLDER_TYPE_SEND) {
				emailConfig.setFolder(sentFolder);
			} else if (folderType == OaEmailConstant.FOLDER_TYPE_DRAFT) {
				emailConfig.setFolder(draftFolder);
			} else if (folderType == OaEmailConstant.FOLDER_TYPE_RECYCLE) {
				emailConfig.setFolder(recycleFolder);
			} else {
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("没有对应信箱");
				return rs;
			}
			emailConfig.setFolderType(folderType);
			boolean b = false;
			if(folderType == OaEmailConstant.FOLDER_TYPE_RECYCLE || folderType == OaEmailConstant.FOLDER_TYPE_DRAFT ){
				 b = OaEmailUtil.forceDeleteEmail(number, emailConfig);
			}else{
				 b = OaEmailUtil.deleteEmail(number, emailConfig);
			}
			if (b) {
				rs.setCode(Result.CODE_OK);
				rs.setMsg("删除成功");
			} else {
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("删除失败");
			}
			return rs;
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	
	/**
	 * 批量删除邮件
	 * @param numbers
	 * @param folderType
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/delBatchEmail")
	public Result delBatchEmail(String numbers, Integer folderType, HttpServletRequest request) {
		Result rs = new Result();
		try {
			if (Validata.isNullOrEmpty(numbers)) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("邮件number不能为空");
				return rs;
			}
			if (folderType == null) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("文件夹类型不能为空");
				return rs;
			}
			OaEmailConfig emailConfig = initConfig(request, OaEmailConstant.TRANSFER_TYPE_GET);
			if (emailConfig.getRunflag() != null && emailConfig.getRunflag().get("errorCode") != null) {
				rs.setCode(emailConfig.getRunflag().get("errorCode"));
				rs.setMsg(emailConfig.getReturnMsg());
				return rs;
			}
			// 1、收件箱 2、发件箱、3草稿箱、4回收箱
			if (folderType == OaEmailConstant.FOLDER_TYPE_INBOX) {
				emailConfig.setFolder(inboxFolder);
			} else if (folderType == OaEmailConstant.FOLDER_TYPE_SEND) {
				emailConfig.setFolder(sentFolder);
			} else if (folderType == OaEmailConstant.FOLDER_TYPE_DRAFT) {
				emailConfig.setFolder(draftFolder);
			} else if (folderType == OaEmailConstant.FOLDER_TYPE_RECYCLE) {
				emailConfig.setFolder(recycleFolder);
			}else {
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("没有对应信箱");
				return rs;
			}
			emailConfig.setFolderType(folderType);
			boolean b = false;
			if(folderType == OaEmailConstant.FOLDER_TYPE_RECYCLE || folderType == OaEmailConstant.FOLDER_TYPE_DRAFT){
				 b = OaEmailUtil.forceDelBatchEmail(numbers, emailConfig);
			}else{
				 b = OaEmailUtil.delBatchEmail(numbers, emailConfig);
			}
			if (b) {
				rs.setCode(Result.CODE_OK);
				rs.setMsg("删除成功");
			} else {
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("删除失败");
			}
			return rs;
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	
	/**
	 * 检查账号
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/checkUserMailExist")
	public Result checkUserMailExist(){
		Result rs = new Result();
		try {
			UserModel user = SessionMap.getObj();
			if (user == null || Validata.isNullOrEmpty(user.getUserId())) {
				rs.setCode(Result.CODE_LOGIN_REQUIRE);
				rs.setMsg(ResMsg.MSG_LOGIN_NEED);
				log.info("没有登录");
				return rs;
			}
			if (StringUtils.isNotBlank(user.getEmail())) {
				String email[] = user.getEmail().split("@");
				if (email.length > 0 && vitoMail.equals(email[1])) {
					rs.setCode(Result.CODE_OK);
				} else {
					rs.setCode(Result.CODE_ERROR);
					rs.setMsg("邮箱账号不是@"+ vitoMail + "邮箱账号，请设置");
					log.info("邮箱账号不是@"+ vitoMail + "邮箱账号，请设置");
				}
			} else {
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("没有邮箱账号，请设置");
				log.info("没有邮箱账号，请设置");
			}
			return rs;
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	
	/**
	 * 保存邮箱
	 * @param userName
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/saveUserMail")
	public Result saveUserMail(String email){
		Result rs = new Result();
		try {
			UserModel user = SessionMap.getObj();
			if (user == null || Validata.isNullOrEmpty(user.getUserId())) {
				rs.setCode(Result.CODE_LOGIN_REQUIRE);
				rs.setMsg(ResMsg.MSG_LOGIN_NEED);
				log.info("没有登录");
				return rs;
			}
			if (Validata.isNullOrEmpty(email)) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("邮件箱不能为空");
				return rs;
			}
			String emailArr[] = email.split("@");
			if (emailArr.length > 0 && vitoMail.equals(emailArr[1])) {
				rs.setCode(Result.CODE_OK);
			} else {
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("邮箱账号不是"+ vitoMail + "邮箱账号，请设置");
				log.info("邮箱账号不是"+ vitoMail + "邮箱账号，请设置");
			}
			if(!contactsService.checkUserMailRepeat(email)){
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("邮件箱已存在");
				return rs;
			}
			boolean b = false;
			//查询用户密码
			String password = oaBaseUserService.getUserPassword(user.getUserId());
			user.setEmail(email);
			OaJamesUser jamesUser = new OaJamesUser();
			jamesUser.setUserName(email);
			jamesUser.setPassword(password.toLowerCase());
			jamesUser.setPasswordHashAlgorithm(OaEmailContant.PASSWORD_HASH_ALGORITHM);
			jamesUser.setVersion(OaEmailContant.VERSION);
			//注册邮件服务器
			b = emailService.saveUserMail(jamesUser, user);
			SessionMap.putObj(user);
			if (b) {
				rs.setCode(Result.CODE_OK);
				rs.setMsg("保存成功");
			} else {
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("保存失败");
			}
			return rs;
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	
	/**
	 * 注册邮件账号
	 * @param jamesUser
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/saveEmailAccount")
	public Result saveEmailAccount(OaJamesUser jamesUser) {
		Result rs = new Result();
		try {
			UserModel user = SessionMap.getObj();
			if (user == null || Validata.isNullOrEmpty(user.getUserId())) {
				rs.setCode(Result.CODE_LOGIN_REQUIRE);
				rs.setMsg(ResMsg.MSG_LOGIN_NEED);
				log.info("没有登录");
				return rs;
			}
			if (StringUtils.isBlank(jamesUser.getUserName())) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("邮件箱不能为空");
				return rs;
			}
			if (StringUtils.isBlank(jamesUser.getPassword())) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("密码不能为空");
				return rs;
			}
			boolean b = emailService.addOaJamesUser(jamesUser);
			if (b) {
				rs.setCode(Result.CODE_OK);
				rs.setMsg("保存成功");
			} else {
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("保存失败");
			}
			return rs;
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	
	/**
	 * 检查用户表邮箱是否重复
	 * @param userName
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/checkUserMailRepeat")
	public Result checkUserMailRepeat(String email){
		Result rs = new Result();
		try {
			UserModel user = SessionMap.getObj();
			if (user == null || Validata.isNullOrEmpty(user.getUserId())) {
				rs.setCode(Result.CODE_LOGIN_REQUIRE);
				rs.setMsg(ResMsg.MSG_LOGIN_NEED);
				log.info("没有登录");
				return rs;
			}
			if (Validata.isNullOrEmpty(email)) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("邮件箱不能为空");
				return rs;
			}
			boolean b = contactsService.checkUserMailRepeat(email);
			if (!b) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("邮箱已存在");
			} else {
				rs.setCode(Result.CODE_OK);
			}
			return rs;
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	
	/**
	 * 保存邮件签名
	 * @param emailSignModel
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/saveEmailSign")
	public Result saveEmailSign(OaEmailSignModel emailSignModel){
		Result rs = new Result();
		try {
			UserModel user = SessionMap.getObj();
			if (user == null || Validata.isNullOrEmpty(user.getUserId())) {
				rs.setCode(Result.CODE_LOGIN_REQUIRE);
				rs.setMsg(ResMsg.MSG_LOGIN_NEED);
				log.info("没有登录");
				return rs;
			}
			if (Validata.isNullOrEmpty(emailSignModel.getSignContent())) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("签名不能为空");
				return rs;
			}
			OaEmailSignModel emailSign = oaEmailSignService.getEmailSignByUserId(user.getUserId());
			if (emailSign != null) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("签名已存在");
				return rs;
			}
			emailSignModel.setUserId(user.getUserId());
			int b = oaEmailSignService.saveEmailSign(emailSignModel);
			if (b > 0) {
				rs.setCode(Result.CODE_OK);
				rs.setMsg("保存成功");
				return rs;
			} else {
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("保存失败");
				return rs;
			}
			
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	
	/**
	 * 修改签名
	 * @param emailSignModel
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateEmailSign")
	public Result updateEmailSign(OaEmailSignModel emailSignModel){
		Result rs = new Result();
		try {
			UserModel user = SessionMap.getObj();
			if (user == null || Validata.isNullOrEmpty(user.getUserId())) {
				rs.setCode(Result.CODE_LOGIN_REQUIRE);
				rs.setMsg(ResMsg.MSG_LOGIN_NEED);
				log.info("没有登录");
				return rs;
			}
			if (Validata.isNullOrEmpty(emailSignModel.getSignId())) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("签名id不能为空");
				return rs;
			}
			if (Validata.isNullOrEmpty(emailSignModel.getSignContent())) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("签名不能为空");
				return rs;
			}
			int b = oaEmailSignService.updateEmailSign(emailSignModel);
			if (b > 0) {
				rs.setCode(Result.CODE_OK);
				rs.setMsg("保存成功");
				return rs;
			} else {
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("保存失败");
				return rs;
			}
			
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	
	/**
	 * 删除签名
	 * @param emailSignModel
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteEmailSign")
	public Result deleteEmailSign(OaEmailSignModel emailSignModel){
		Result rs = new Result();
		try {
			UserModel user = SessionMap.getObj();
			if (user == null || Validata.isNullOrEmpty(user.getUserId())) {
				rs.setCode(Result.CODE_LOGIN_REQUIRE);
				rs.setMsg(ResMsg.MSG_LOGIN_NEED);
				log.info("没有登录");
				return rs;
			}
			if (Validata.isNullOrEmpty(emailSignModel.getSignId())) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("签名id不能为空");
				return rs;
			}
			if (emailSignModel.getStatus() == null) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("签名状态不能为空");
				return rs;
			}
			int b = oaEmailSignService.updateEmailSign(emailSignModel);
			if (b > 0) {
				rs.setCode(Result.CODE_OK);
				rs.setMsg("删除成功");
				return rs;
			} else {
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("删除失败");
				return rs;
			}
			
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	
	/**
	 * 查询邮件签名
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getEmailSign")
	public Result getEmailSign(){
		Result rs = new Result();
		try {
			UserModel user = SessionMap.getObj();
			if (user == null || Validata.isNullOrEmpty(user.getUserId())) {
				rs.setCode(Result.CODE_LOGIN_REQUIRE);
				rs.setMsg(ResMsg.MSG_LOGIN_NEED);
				log.info("没有登录");
				return rs;
			}
			OaEmailSignModel emailSign = oaEmailSignService.getEmailSignByUserId(user.getUserId());
			rs.setCode(Result.CODE_OK);
			rs.setData(emailSign);
			return rs;
			
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	
	/**
	 * 查询未读邮件
	 * @param request
	 * @param count
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getUnreadMessageList")
	public Result getUnreadMessageList(HttpServletRequest request, Integer count){
		Result rs = new Result();
		try {
			UserModel user = SessionMap.getObj();
			if (user == null || Validata.isNullOrEmpty(user.getUserId())) {
				rs.setCode(Result.CODE_LOGIN_REQUIRE);
				rs.setMsg(ResMsg.MSG_LOGIN_NEED);
				log.info("没有登录");
				return rs;
			}
			if (count == null || count == 0) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("数量不能为空");
				return rs;
			}
			OaEmailConfig emailConfig = initConfig(request, OaEmailConstant.TRANSFER_TYPE_GET);
			if (emailConfig.getRunflag() != null && emailConfig.getRunflag().get("errorCode") != null) {
				rs.setCode(emailConfig.getRunflag().get("errorCode"));
				rs.setMsg(emailConfig.getReturnMsg());
				return rs;
			}
	        emailConfig.setFolder(inboxFolder);
	        rs.setCode(Result.CODE_OK);
	        rs.setData(OaEmailUtil.getUnreadMessageList(count, emailConfig));
			return rs;
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/updateFlagStatus")
	public Result updateFlagStatus(HttpServletRequest request, String numbers, Integer status) {
		Result rs = new Result();
		try {
			UserModel user = SessionMap.getObj();
			if (user == null || Validata.isNullOrEmpty(user.getUserId())) {
				rs.setCode(Result.CODE_LOGIN_REQUIRE);
				rs.setMsg(ResMsg.MSG_LOGIN_NEED);
				log.info("没有登录");
				return rs;
			}
			if (StringUtils.isBlank(numbers)) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("number不能为空");
				return rs;
			}
			if (status == null) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("状态不能为空");
				return rs;
			}
			OaEmailConfig emailConfig = initConfig(request, OaEmailConstant.TRANSFER_TYPE_GET);
			if (emailConfig.getRunflag() != null && emailConfig.getRunflag().get("errorCode") != null) {
				rs.setCode(emailConfig.getRunflag().get("errorCode"));
				rs.setMsg(emailConfig.getReturnMsg());
				return rs;
			}
	        emailConfig.setFolder(inboxFolder);
	        emailConfig.setFolderType(OaEmailConstant.FOLDER_TYPE_INBOX);
	        boolean b = OaEmailUtil.updateFlagStatus(numbers, status, emailConfig);
	        if (b) {
	        	rs.setCode(Result.CODE_OK);
				rs.setMsg("修改成功");
				return rs;
	        } else {
	        	rs.setCode(Result.CODE_ERROR);
				rs.setMsg("修改失败");
	        	return rs;
	        }
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	
	/**
	 * 下载附件
	 * @param number
	 * @param folderType
	 * @param name
	 * @param sid
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/downloadFile")
	public Result downloadFile(Long number, Integer folderType, String fileName, Integer fileId, HttpServletResponse response, HttpServletRequest request) {
		Result rs = new Result();
		try {
			UserModel user = SessionMap.getObj();
			if (user == null || Validata.isNullOrEmpty(user.getUserId())) {
				rs.setCode(Result.CODE_LOGIN_REQUIRE);
				rs.setMsg(ResMsg.MSG_LOGIN_NEED);
				log.info("没有登录");
				return rs;
			}
			if (Validata.isNullOrEmpty(fileName)) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("文件名不能为空");
				return rs;
			}
			if (fileId == null) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("fileId不能为空");
				return rs;
			}
			if (number == null) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("number不能为空");
				return rs;
			}
			if (folderType == null) {
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("文件夹类型不能为空");
				return rs;
			}
			String folderName = "";
			// 1、收件箱 2、发件箱、3草稿箱
			if (folderType == OaEmailConstant.FOLDER_TYPE_INBOX) {
				folderName = inboxFolder;
			} else if (folderType == OaEmailConstant.FOLDER_TYPE_SEND) {
				folderName = sentFolder;
			} else if (folderType == OaEmailConstant.FOLDER_TYPE_DRAFT) {
				folderName = draftFolder;
			} else {
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("没有对应信箱");
				return rs;
			}
			boolean b = false;
			try {
//				Properties props = new Properties();
//				String sessionid = request == null ? SpringApplicationContext.getSessionId() : SpringApplicationContext.getSessionId(request);
//				String ip = projectIP;
//				Store store = null;
////				try {
////					ip = InetAddress.getLocalHost().getHostAddress();
////				} catch (UnknownHostException e) {
////					log.info("邮件获取ip失败");
////					e.printStackTrace();
////				}
//				
//				String path = request.getScheme()+"://"+ip+":"+request.getServerPort();
//				String hrefPath = path + StringUtil.getWebRootPath() + proxyAuthUrl + sessionid+"&userid="+user.getUserId();
//				props.setProperty("mail.imap.proxyauth.user", hrefPath);
//				props.setProperty("mail.imap.class", VitoImapStore.class.getName());
//				props.setProperty("LOGINDISABLED", "true");
//				Session session = Session.getInstance(props);
//				session.addProvider(new VitoImapProvider(Provider.Type.STORE, "imap", null, "Sun Microsystems, Inc", null));;
//				URLName urln = new URLName(url);
//				try {
//					store = session.getStore(urln);
//					store.connect();
//				} catch (Exception e) {
//					log.info("连接邮件服务器失败");
//				}
				OaEmailConfig emailConfig = initConfig(request, OaEmailConstant.TRANSFER_TYPE_GET);
				if (emailConfig.getRunflag() != null && emailConfig.getRunflag().get("errorCode") != null) {
					rs.setCode(emailConfig.getRunflag().get("errorCode"));
					rs.setMsg(emailConfig.getReturnMsg());
					return rs;
				}
				Store store = emailConfig.getStore();
				// 获得收件箱 
				IMAPFolder folder =  (IMAPFolder)store.getFolder(folderName); 
				// 以读写模式打开收件箱 
				folder.open(Folder.READ_WRITE); 
				// 获得收件箱的邮件列表 
				Message message = folder.getMessageByUID(number);
				if (message != null) {
					//MimeMessage msg = (MimeMessage) message; 
					MimeMessage cmsg = new MimeMessage((MimeMessage)message);
					saveAttachment(cmsg, fileName, fileId, response);
					b = true;
				}
				//判断发件文件夹是否打开如果打开则将其关闭
				if(folder!=null && folder.isOpen()){
					folder.close(true); 
				}
				//判断邮箱存储是否打开如果打开则将其关闭
				if(store!=null && store.isConnected()){
					store.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (b) {
				rs.setCode(Result.CODE_OK);
				rs.setMsg("下载成功");
			} else {
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("下载失败");
			}
			return rs;
		} catch (Exception e) {
			log.error("执行异常：",e);
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("执行异常");
			return rs;
		}
	}
	
	/**
	 * 根据字符串创建本地目录 并按照日期建立子目录返回
	 * @param path 
	 * @return 
	 */
	public static String getFolder(String path) {
		SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
		path += "/" + formater.format(new Date());
		File dir = new File(path);
		if (!dir.exists()) {
			try {
				dir.mkdirs();
			} catch (Exception e) {
				return "";
			}
		}
		return path;
	}
	
	/**
	 * 依据原始文件名生成新文件名
	 * @return
	 */
	public static String getNewFileName(String fileName) {
		String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
		return newFileName;
	}
	
	 //下载附件
    public void saveAttachment(Part part, String name, Integer id, HttpServletResponse response) throws Exception {
    	String fileName = "";
    	if (part.isMimeType("multipart/*")) {
    		Multipart mp = (Multipart) part.getContent();
    		for (int i = 0; i < mp.getCount(); i++) {
    			BodyPart mpart = mp.getBodyPart(i);
    			String disposition = mpart.getDisposition();
    			if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)) || (disposition.equals(Part.INLINE)))) {
    				fileName = mpart.getFileName();
    				if (fileName.toLowerCase().indexOf("utf") != -1){
    					fileName = MimeUtility.decodeText(fileName);
    				}
    				System.out.println(i + "," + fileName);
    				if (name.equals(fileName) && id == i) {
    					saveFile(fileName, mpart.getInputStream(), response);
    				}
    			} else if (mpart.isMimeType("multipart/*")) {
    				saveAttachment(mpart, name, id, response);
    			} else {
    				fileName = mpart.getFileName();
    				if ((fileName != null) && (fileName.toLowerCase().indexOf("utf-8") != -1)) {
						fileName = MimeUtility.decodeText(fileName);
						//saveFile(fileName, mpart.getInputStream());
						System.out.println(i + "," + fileName);
						if (name.equals(fileName) && id == i) {
	    					saveFile(fileName, mpart.getInputStream(), response);
	    				}
					}
    			}
			}
    	} else if (part.isMimeType("message/rfc822")) {
    		saveAttachment((Part) part.getContent(), name, id, response);
    	}
    }
    
  //保存附件
    public void saveFile(String fileName, InputStream is, HttpServletResponse response) throws Exception {
		//清空response
		response.reset();
		response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
		response.setHeader("Pragma", "No-cache");  
		response.setHeader("Cache-Control", "No-cache");  
		response.setDateHeader("Expires", 0);
		int bytesRead = 0;
		//创建数据缓冲区
        byte[] buffer = new byte[1024*1024];
        //通过response对象获取OutputStream流
        ServletOutputStream streamOut = response.getOutputStream();
        //将InputStream流写入到buffer缓冲区
        while ((bytesRead = is.read(buffer)) > 0) {
        	//使用OutputStream将缓冲区的数据输出到客户端浏览器
            streamOut.write(buffer, 0, bytesRead);
        }
        
//        int data;  
//        while((data = is.read()) != -1) {  
//        	streamOut.write(data);  
//        	streamOut.flush();
//        }  
//        is.close();  
//        streamOut.close();
        
        streamOut.flush();
        streamOut.close();
        is.close();
    }
	
}
